package com.chinasoft.utils;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by YE on 2018/5/17.
 */
public class EmailUtils {

    public static boolean sendEmail(String user, String msg) {
        try {

            InputStream is = EmailUtils.class.getResourceAsStream("/mail.properties");
            final Properties p = new Properties();
            p.load(is);
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    String userName = p.getProperty("mail.user");
                    String password = p.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            Session mailSession = Session.getInstance(p, authenticator);
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            InternetAddress form = new InternetAddress(p.getProperty("mail.user"));
            message.setFrom(form);
            // 设置收件人
            InternetAddress to = new InternetAddress(user);
            message.setRecipient(Message.RecipientType.TO, to);
            // 设置邮件标题
            message.setSubject("论坛注册");
            // 设置邮件的内容体
            message.setContent(msg, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return false;
    }
}

